package com.czyxy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by mike on 6/8/17.
 */
@Controller
public class ExportController {
    @Autowired
    JsonService jsonService;
    @Autowired
    StudentFeeService studentFeeService;
    @RequestMapping("/download")
    public String export(HttpServletResponse res, HttpServletRequest req) {
        String fileName = null;
        try {
            fileName =jsonService.saveJsonFile(studentFeeService.getAllStudentFee());
        }catch (Exception e){
            e.printStackTrace();
        }

        if (fileName != null) {
            //当前是从该工程的WEB-INF//+//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
//            String realPath = req.getServletContext().getRealPath(
//                    "//WEB-INF//");
            File file = new File(fileName);
            if (file.exists()) {
                res.setContentType("application/force-download");// 设置强制下载不打开
                res.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024000];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = res.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
}
